<template>
  <div class="content">
    <div class="head-top">
      <dc-header :icon="'icon-header-back'" :title="typeTitle"></dc-header>
      <div id="1">
        <dc-row type="flex" justify="end" class="bg-white">
          <dc-col span="6">
            <span class="money">{{typenumTitle}}</span>
          </dc-col>
          <dc-col span="18">
            <input class="moneynum" type="tel" maxlength="13" placeholder="0" v-model="expenditure.accountNum"/>
          </dc-col>
        </dc-row>
        <div v-if="expenditure.accountType.value==='2'">
          <mt-cell title="本月摊销" :value="residueNum"></mt-cell>
          <mt-cell title="待摊余额" :value="residueOddNum"></mt-cell>
        </div>
        <div class="mt30">
          <mt-cell title="类别" :value="expenditureValue" ></mt-cell>
          <mt-cell title="记账类型" :value="expenditure.accountType.label" ></mt-cell>
          <inputDateselect label="日期" v-if="expenditure.accountType.value==='1'" datepickerType="nyr"
                           v-model="expenditure.startnyr"></inputDateselect>
          <inputDateselect name="起始时间" label="起始时间"
                           datepickerType="ny"
                           v-if="expenditure.accountType.value==='2' || expenditure.accountType.value==='3'"
                           v-model="expenditure.startny"
                           :meiyong="getresiduePeriod"
          ></inputDateselect>
          <inputSelectCustom placeholder="请选择" type="text" showtype="noicon"
                             v-validate="{ rules: { required: true } }"
                             name="持续周期"
                             label="持续周期"
                             :upscrolldata="timeSlot"
                             v-model="expenditure.duration"
                             v-if="expenditure.accountType.value==='3'"
          >
            <mt-cell :title="'持续周期'" v-model="expenditureDurationLaber" is-link></mt-cell>
          </inputSelectCustom>
          <inputSelectCustom placeholder="请选择" type="text" showtype="noicon"
                             v-validate="{ rules: { required: true } }"
                             name="摊销周期"
                             label="摊销周期"
                             :upscrolldata="timeSlot"
                             v-model="expenditure.duration"
                             v-if="expenditure.accountType.value==='2'"
          >
            <mt-cell :title="'摊销周期'" v-model="expenditureDurationLaber" is-link></mt-cell>
          </inputSelectCustom>
          <mt-cell v-if="expenditure.accountType.value==='2' || expenditure.accountType.value==='3'"
                   :title="'截止时间'" v-model="residuePeriod"></mt-cell>

        </div>
        <div class="mt30">
          <mt-field class="kctextleft" :attr="{maxlength:200}" label="备注" placeholder="请输入" v-model="expenditure.remark"></mt-field>
        </div>
        <div class="prompt" v-if="isDefault !== 1">
          注：修改或删除数据请务必谨慎，如改变费用时间或者周期或删除条目，将影响历史数据的准确性
        </div>
        <div class="buttonBox" v-if="isDefault !== 1">
          <dc-row type="flex" justify="start">
            <dc-col span="12" type="default" class="leftbuttonBox">
              <mt-button @click="deletecategoryitem()">删除</mt-button>
            </dc-col>
            <dc-col type="primary" span="12" class="rightbuttonBox">
              <mt-button @click="pushExpenditure(false)">保存</mt-button>
            </dc-col>
          </dc-row>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import header from '@/common/plugins/header';
  import {col, row} from '@/common/Flex';
  import inputSelectCustom from '@/common/plugins/input/inputSelectCustom.vue';
  import inputDateselect from '@/common/plugins/input/inputDateselect.vue';
  import inputSelect from '@/common/plugins/input/inputSelect.vue';
  import pickerBox from '@/common/plugins/pickerBox.vue';
  import api from '../../../common/api/account';
  import mintUi from '@/common/mintUi';
  let timeSlot = [{
    label: '3个月',
    value: '1'
  }, {
    label: '6个月',
    value: '2'
  }, {
    label: '9个月',
    value: '3'
  }, {
    label: '12个月',
    value: '4'
  }, {
    label: '24个月',
    value: '5'
  }, {
    label: '自定义',
    value: '6'
  }];
  let dataInfo = {
    selected: '1',
    accountTypelist: [{
      label: '单次支出',
      value: '1'
    }, {
      label: '固定支出',
      value: '3'
    }, {
      label: '摊销费用',
      value: '2'
    }],
    accountTypelist2: [{
      label: '单次收入',
      value: '1'
    }],
    timeSlot: timeSlot,
    slots: [
      {
        flex: 1,
        defaultIndex: 0,
        values: [],
        className: 'slot1',
        textAlign: 'center'
      }, {
        flex: 1,
        defaultIndex: 0,
        values: [],
        className: 'slot3',
        textAlign: 'center'
      }
    ],
    expenditure: {
      accountCode: '',
      accountSubCode: '',
      accountType: '1',
      duration: '',
      durationLaber: '',
      startnyr: '请选择',
      startny: '请选择',
      accountNum: '',
      remark: ''
    },
    isDefault: 0,
    residuePeriod: 0,
    expenditureDurationLaber: '请选择',
    expenditureValue: '请选择',
    id: 0,
    typeTitle: '',
    typenumTitle: ''
  };

  export default {
    data () {
      return dataInfo;
    },
    computed: {
      residueNum () {
        return (this.expenditure.accountNum / parseInt(this.expenditureDurationLaber)).toFixed(2);
      },
      residueOddNum () {
        return (this.expenditure.accountNum / parseInt(this.expenditureDurationLaber) * parseInt(this.getresiduePeriod)).toFixed(2);
      },
      getresiduePeriod () {
        console.log(this.expenditure.startny);
        if (this.expenditure.accountType.value !== '1') {
          let beginTime = this.expenditure.startny.split('-');
          let beginTimeNum = Date.parse(new Date(beginTime[0], beginTime[1] - 1, beginTime[2] || 1));
          let endTime = new Date(beginTime[0], beginTime[1] - 1 + parseInt(this.expenditureDurationLaber) - 1, beginTime[2] || 1);
          let endTimeNum = Date.parse(endTime);
          let newTimeNum = Date.parse(new Date());
          //let diff = endTimeNum - beginTimeNum;
          let diff2 = endTimeNum - newTimeNum > 0 ? endTimeNum - newTimeNum : 0;
          //this.residuePeriod = (beginTimeNum < newTimeNum) ? ((diff2 / 60 / 60 / 24 / 30 / 1000).toFixed() + '个月') : this.expenditureDurationLaber;
          this.residuePeriod = endTime.getFullYear() + '-' + (endTime.getMonth() + 1);
          return (beginTimeNum < newTimeNum) ? (diff2 / 60 / 60 / 24 / 30 / 1000).toFixed() : parseInt(this.expenditureDurationLaber);
        } else {
          return 0;
        }
      }
      // 计算属性的 getter
    },
    components: {
      'dc-header': header,
      'dc-col': col,
      'dc-row': row,
      inputSelect,
      inputDateselect,
      inputSelectCustom,
      pickerBox
    },
    methods: {
      getExpenditureCategoryValue: function (e) {
        this.expenditureValue = e[0].accountName + (e[1] ? '>' + e[1].accountName : '');
        this.expenditure.accountCode = e[0].accountCode;
        this.expenditure.accountSubCode = e[1] ? e[1].accountCode : '';
      },
      changeValue: function (picker, values) {
        if (values[0]) {
          let arr = this.slots[0].values.filter(function (val) {
            if (val.accountCode === values[0].accountCode) {
              return val;
            }
          });
          this.slots[1].values = arr[0].subCategory;
        }
      },
      openPrompt: function (mes, obj) {
        let that = this;
        mintUi.openPrompt(mes, {inputType: 'text', inputPlaceholder: '小于120个月'}).then(function (e) {
          if (parseInt(e) && parseInt(e) < 120) {
            that[obj] = parseInt(e) + '个月';
            that.expenditure.duration = '';
          } else {
            that.openPrompt('您输入的月份无效', obj);
          }
        }, function () {
          that.expenditure.duration = '';
        }).catch(function () {
          that.expenditure.duration = '';
        });
      },
      pushExpenditure (e) {
        let that = this;
        let data = {};
        data.duration = parseInt(this.expenditureDurationLaber);
        data.accountNum = this.expenditure.accountNum;
        data.remark = this.expenditure.remark;
        let beginTime = this.expenditure.accountType.value === '1' ? this.expenditure.startnyr : this.expenditure.startny;
        let beginTimeArr = beginTime.split('-');
        data.beginTime = Date.parse(new Date(beginTimeArr[0], beginTimeArr[1] - 1, beginTimeArr[2] || 1));
        data.id = this.id;
        var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
        if (!reg.test(data.accountNum)) {
          mintUi.openToast('请填写数字金额');
          return;
        }
        api.changecategoryitem(data).then(function (res) {
          mintUi.openAlert('成功').then(() => {
            that.$router.go(-1);
          });
        });
      },
      deletecategoryitem () {
        mintUi.openConfirm('确认删除吗？').then(() => {
          api.deletecategoryitem(this.id).then(res => {
            this.$router.go(-1);
          });
        });
      },
      formatDate: function (date, type) {
        let time = new Date(date);
        let formatdate = {
          year: time.getFullYear(),
          month: time.getMonth(),
          date: time.getDate()
        };
        formatdate.month = formatdate.month + 1;
        let returnDate = '';
        switch (type) {
          case 1:
            returnDate = formatdate.year + '-' + formatdate.month + '-' + formatdate.date;
            break;
          case 2:
            returnDate = formatdate.year + '-' + formatdate.month;
            break;
        }
        return returnDate;
      }
    },
    created () {
      api.getcategoryList({'accountFlag': 1}).then(res => { //点击单个选项获取店铺列表api
        this.slots[0].values = res || [];
        this.slots[1].values = res && (res[0].subCategory || []);
      });
      api.getDetail(this.$route.params.id).then(res => {
        this.accountFlag = res.accountFlag;
        this.expenditure.accountNum = res.accountNum;
        this.expenditure.accountCode = res.accountCode;
        if (res.accountFlag === 2) {
          this.expenditure.accountType = this.accountTypelist.filter(val => val.value === (res.accountType + ''))[0];
        } else {
          this.expenditure.accountType = this.accountTypelist2.filter(val => val.value === (res.accountType + ''))[0];
        }
        this.typeTitle = res.accountFlag === 1 ? '编辑收入' : '编辑支出';
        this.typenumTitle = res.accountFlag === 1 ? '收入金额' : (this.expenditure.accountType === 2 ? '摊销总额' : '支出金额');
        this.id = res.id;
        //this.residuePeriod = res.residuePeriod + '个月';
        this.expenditure.remark = res.remark;
        this.expenditure.accountSubCode = res.accountSubCode;
        this.expenditure.startnyr = this.formatDate(res.beginTime, 1);
        this.expenditure.startny = this.formatDate(res.beginTime, 2);
        this.expenditureValue = res.accountName + (res.accountSubName ? '>' + res.accountSubName : '');
        this.expenditureDurationLaber = res.duration ? res.duration + '个月' : '请选择';
        this.isDefault = res.isDefault;
      });
    },
    watch: {
      selected: function () {
        api.getcategoryList({'accountFlag': this.selected}).then(res => { //点击单个选项获取店铺列表api
          this.slots[0].values = res || [];
          this.slots[1].values = res && (res[0].subCategory || []);
        });
      },
      expenditure: {
        handler (newValue, oldValue) {
          if (newValue.duration === '6') {
            this.openPrompt('请输入具体月份', 'expenditureDurationLaber');
            //this.expenditure.duration === '';
          } else {
            this.expenditureDurationLaber = timeSlot[newValue.duration - 1] ? timeSlot[newValue.duration - 1].label : this.expenditureDurationLaber;
          }
        },
        deep: true
      }
    }
  };
</script>
<style lang="scss" scoped>
  @import "../../../assets/css/variable";

  .money {
    line-height: px2rem(140px);
    font-size: px2rem(35px);
    font-weight: bold;
  }

  .moneynum {
    height: px2rem(140px);
    border: none;
    outline: none;
    text-align: right;
    color: #f8c840;
    font-size: px2rem(50px);
    padding: 0;
    margin: 0;
    width: 90%;
  }

  .green {
    color: #59cd9c;
  }

  .buttonBox {
    position: fixed;
    bottom: 0;
    width: 100%;
  }

  .leftbuttonBox {
    height: px2rem(100px);
    background: #456878;
    button {
      color: #fff;
      background: #f15b59;
    }
  }

  .rightbuttonBox {
    height: px2rem(100px);
    background: #456878;
    button {
      color: #fff;
      background: $theme-color;
    }
  }

  .rightbuttonBox, .leftbuttonBox {
    button {
      width: 100%;
      border-radius: 0;
      box-shadow: none;
      height: px2rem(100px);
      font-size: px2rem(30px);
    }
  }

  .prompt {
    margin: px2rem(15px);
    padding: px2rem(15px);
    box-sizing: border-box;
    color: #666;
    background: #ffde97;
  }
</style>
<style lang="scss">
  .kctextleft .mint-field-core {
    text-align: right;
  }
</style>
